package com.mamingchao.springcloud.eureka.testcase;


import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;

import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by mamingchao on 2020/9/1.
 */
public class SingletonHystrixTest extends HystrixCommand {

    private AtomicInteger account = new AtomicInteger();


    protected SingletonHystrixTest(HystrixCommandGroupKey group) {
        super(group);
    }

    @Override
    protected String run() throws Exception {
        int a = 1/0;

//        TimeUnit.SECONDS.sleep(1);
        System.out.println("This is your " + account.incrementAndGet() + "times of coming into run function!");
        return "run logic";
    }

    @Override
    protected String getFallback() {
        System.out.println("You have come into fallback function!");
        return "fallback logic";
    }

    /**
     * HystrixTestMain command executed multiple times - this is not permitted.
     * This instance can only be executed once. Please instantiate a new instance.
     * 一个HystrixCommand 实例不可以多次执行 excute方法
     *
     * 这里的key 是Hystrix线程池分组，也叫舱壁，用于做线程隔离
     * @param args
     */
    public static void main(String[] args) {
        SingletonHystrixTest testMain = new SingletonHystrixTest(HystrixCommandGroupKey.Factory.asKey("serviceProvicer"));

        try {

            //excute方法是同步阻塞方式。执行excite，Hystrix会新建一个线程执行run，然后一直阻塞着
            //知道run方法返回结果
//            System.out.println("excute result is " + testMain.execute());

            //queue方法是异步非阻塞方式
            Future<Object> futureResult = testMain.queue();

            System.out.println("future result is " + futureResult.get());

//            for(int i=0;i<5;i++) {
//                new Thread(()-> {
//                    testMain.execute();
//                }).start();
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
